package com.lightjet.macross.base.auth.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.lightjet.macross.base.auth.feign.BaseAuthRemoteClient;
import com.lightjet.macross.base.upms.domain.AppClient;
import com.lightjet.macross.base.upms.service.AppClientService;
import com.lightjet.macross.base.upms.service.LoginAdapterService;
import com.lightjet.macross.common.dto.ResponseDTO;
import com.lightjet.macross.common.util.RespUtil;
import com.lightjet.macross.common.util.SpringUtil;
import io.netty.util.internal.StringUtil;
import lombok.extern.java.Log;
import org.apache.commons.codec.binary.Base64;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.HashMap;

@Controller
@RequestMapping("/")
@Scope("request")
@Log
public class SSOLoginController {

    @Resource
    private DefaultKaptcha defaultKaptcha;

    @Resource
    LoginAdapterService loginAdapterService;

    @Resource
    AppClientService appClientService;

    @Resource
    private BaseAuthRemoteClient baseAuthRemoteClient;
    /**
     * 生成验证码
     * @param response
     * @param session
     * @throws IOException
     */
    @GetMapping("captcha")
    public void captcha(String type,HttpServletResponse response,
                        HttpSession session) throws IOException {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            if(!StringUtil.isNullOrEmpty(type))
            {
                defaultKaptcha = SpringUtil.getBean("kaptcha_"+type,DefaultKaptcha.class);
            }
            String createText = defaultKaptcha.createText();
            session.setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, createText);

            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    @ResponseBody
    @RequestMapping(value="captcha",method = RequestMethod.POST)
    public boolean CheckCaptcha(String verifyCode,HttpSession session)
    {
        return verifyCode.equals(session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY));
    }

    @RequestMapping(value = "ssologin", method = RequestMethod.GET)
    public String Login(String clientid, HashMap<String,Object> map, HttpServletRequest request)
    {
        clientid = StringUtil.isNullOrEmpty(clientid)? "vda-ui" : clientid;

        AppClient appClient = appClientService.FindByClientid(clientid);

        map.put("clientdes",appClient == null? "" :appClient.getDescription());
        map.put("clientid",clientid);
        map.put("clientip",request.getRemoteAddr());
        /*if(!StringUtil.isNullOrEmpty(siv)) //集成同一认证
        {
            HttpHeaders headers = new HttpHeaders();
            MultiValueMap<String,String> parammap = new LinkedMultiValueMap<>();
            parammap.add("caSession",siv);
            parammap.add("caSiv","");
            HttpEntity<MultiValueMap<String,String>> httpEntity = new HttpEntity<MultiValueMap<String,String>>(parammap,headers);
            ResultDTO res =  restTemplate.postForObject(k2wfsvr+"DailyReport/GetLoginId",httpEntity,ResultDTO.class);
            if(res.getContent()!=null)
            {
                String userid = res.getContent().toString();
                sysUserService = SpringUtil.getBean("ht802",PlatUserAuthService.class);
                SimpleUserDTO userDTO = sysUserService.GetSimpleUserInfo(userid);
                map.put("token",JwtUtil.signForUser(userDTO.getId()+"", userDTO.getPassword(),"ht802"));
            }
        }*/
        return "ssologin";
    }

/*    @PostMapping(value = "ssologin")
    public String Login()
    {
        return "";
    }*/

    //根据登录方式计算密码的加密值 并通过webapi 调用获取token
    @PostMapping("ssologin")
    @ResponseBody
    public ResponseDTO<HashMap> SSOLogin(String uid, String pwd, String type,String clientid, HttpServletRequest resq)
    {
        String p = new String(Base64.decodeBase64(pwd.getBytes(StandardCharsets.UTF_8)));
        String u = new String(Base64.decodeBase64(uid.getBytes(StandardCharsets.UTF_8)));
        if(!StringUtil.isNullOrEmpty(type)) {
            loginAdapterService = SpringUtil.getBean(type,LoginAdapterService.class);
        }
        String salt = loginAdapterService.GetSaltValueByUserName(u);
        String secret = loginAdapterService.GetEncodedPwd(p,salt,null);
        //MultiValueMap<String ,String> parms = new LinkedMultiValueMap<>();
        AppClient appClient = appClientService.FindByClientid(clientid);

/*        parms.add("password",secret);
        parms.add("username",u);
        parms.add("client_id",clientid);
        parms.add("client_secret",appClient.getSecret());
        parms.add("scope","all");
        parms.add("grant_type","password");*/
        try {
            HashMap resp = baseAuthRemoteClient.GetToken(
                    clientid, appClient.getSecret(), MessageFormat.format("{0}|{1}:{2}", u, type, clientid), secret, "all", "", "password");
            //HashMap resp =  new RestTemplate().postForObject(resq.getRequestURL().toString().replace("ssologin","")+"oauth/token",parms, HashMap.class);
            resp.put("entryuri", appClient.getEntryuri());
            return RespUtil.CreateOK(resp);
        }
        catch (Exception e)
        {
            return RespUtil.CreateError("用户认证失败："+e.getMessage());
        }
    }

    @PostMapping("oauth/freshtoken")
    @ResponseBody
    public ResponseDTO<HashMap> FreshToken(String client_id, String refresh_token, HttpServletRequest resq)
    {
        //MultiValueMap<String ,String> parms = new LinkedMultiValueMap<>();
        AppClient appClient = appClientService.FindByClientid(client_id);
        HashMap resp = baseAuthRemoteClient.GetToken(
                client_id,appClient.getSecret(),"","","",refresh_token,"refresh_token");
        //HashMap resp =  new RestTemplate().postForObject(resq.getRequestURL().toString().replace("ssologin","")+"oauth/token",parms, HashMap.class);
        //resp.put("entryuri",appClient.getEntryuri());
        return RespUtil.CreateOK(resp);

    }

//    private static String getRealIp(HttpServletRequest request)
//    {
//        String ip = request.getHeader("x-forwarded-for");
//        if(ip != null && ip.length() !=0 && !"unknown".equalsIgnoreCase(ip))
//        {
//            if(ip.contains(","))
//            {
//                ip = ip.split(",")[0];
//            }
//        }
//        if(ip != null && ip.length() !=0 && !"unknown".equalsIgnoreCase(ip)) {
//            ip =request.getHeader("Proxy-Client-IP");
//        }
//        if(ip != null && ip.length() !=0 && !"unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("WL-Proxy-Client-IP");
//        }
//        if(ip != null && ip.length() !=0 && !"unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("HTTP_CLIENT_IP");
//        }
//        if(ip != null && ip.length() !=0 && !"unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
//        }
//        if(ip != null && ip.length() !=0 && !"unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("X-Real-IP");
//        }
//        if(ip != null && ip.length() !=0 && !"unknown".equalsIgnoreCase(ip)) {
//            ip = request.getRemoteAddr();
//        }
//        return ip;
//    }

}
